"use strict";

import Vue from 'vue';
import axios from "axios";
import router  from "@/router";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
  baseURL:"http://localhost:8080/",
};

const _axios = axios.create(config);

//axios的请求拦截器，可以对所有的axios请求进行统一处理
_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
      const token = localStorage.getItem("token");
      const userToken = window.localStorage.getItem("userToken");
      const identity = localStorage.getItem("identity");
      const identity1 = localStorage.getItem("identity1");
      if (token && identity) {
          config.headers["token"] = token;
          config.headers["identity"] = identity;
      }
      else if (userToken) {
          config.headers["userToken"] = userToken;
          config.headers["identity1"] = identity1
      }
      else {
          const currentPath = router.currentRoute.path;
          // 如果当前路径是用户相关且非登录页
          if (currentPath.startsWith("/user") && !currentPath.startsWith("/user/login")) {
              router.push("/user/login").catch(err => {
                  if (err.name !== 'NavigationDuplicated') throw err;
              });
          }
          // 如果是其他路径（如管理员相关）
          else if (currentPath !== "/admin/login") {
              router.push("/admin/login").catch(err => {
                  if (err.name !== 'NavigationDuplicated') throw err;
              });
          }
      }
      return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

//axios响应拦截器 可以对axios的响应进行统一的处理
// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
      if (response.data.code === 10001) {
          const currentPath = router.currentRoute.path;
          // 排除已经在登录页的情况
          if (currentPath !== '/admin/login') {
              router.push('/admin/login').catch(err => {
                  // 忽略重复导航错误
                  if (err.name !== 'NavigationDuplicated') {
                      throw err;
                  }
              });
          }
          else if(currentPath !== '/user/login'){
              router.push('/user/login').catch(err => {
                  // 忽略重复导航错误
                  if (err.name !== 'NavigationDuplicated') {
                      throw err;
                  }
              });
          }
      }
      return response;
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function(Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;
